#include "mprpcchannel.h"
#include "rpcheader.pb.h"     // for mprpc::RpcHeader rpcHeader;
#include "mprpcapplication.h" // 调用内部的配置文件

#include <google/protobuf/descriptor.h> // for ::google::protobuf::MethodDescriptor
#include <google/protobuf/message.h>    // for const ::google::protobuf::Message *request
#include <string>
#include <netinet/in.h> // htonl 网络字节序

#include <sys/types.h> //socket
#include <sys/socket.h>
#include <error.h>
#include <arpa/inet.h> // for int inet_pton(int af, const char *src, void *dst);
#include <unistd.h> // for close(fd)
#include <zookeeperutil.h>

// 自定义删除器， 用于关闭文件描述符
auto fd_closer = [] (int *fd) {
    if (fd && -1 != *fd) {
        close(*fd);
        *fd = -1;  // 标记为已关闭， 防止重复关闭
    }
    delete fd;  // 删除指向文件描述符的指针
};

/*
    约定的消息格式是head_size + service_name method_name args_size + args
                   head_size = sizeof(service_name method_name args_size + args)
 */

// 所有 通过stub代理对象调用的rpc方法， 都走到这里了， 统一做rpc方法调用的数据序列化和网络发送
void MprpcChannel::CallMethod(const ::google::protobuf::MethodDescriptor *method, ::google::protobuf::RpcController *controller, const ::google::protobuf::Message *request, ::google::protobuf::Message *response, ::google::protobuf::Closure *done)
{
    // Gets the service to which this method belongs.  Never nullptr.
    // 获取此方法所属的服务。从不nullptr。
    const ::google::protobuf::ServiceDescriptor *pservicedesc = method->service();
    std::string service_name = pservicedesc->name(); // service_name
    std::string method_name = method->name();        // method_name

    // 获取参数的序列化字符串长度 args_size
    uint32_t args_size = 0;
    std::string args_str;
    if (!request->SerializeToString(&args_str))
    {
        std::cout << "serialize request to string error!" << std::endl; // 后期改到日志上
        controller->SetFailed("serialize request to string error!");
        return;
    }
    else
    {
        args_size = args_str.size();
    }
    // 定义rpc的请求头
    mprpc::RpcHeader rpcHeader;
    rpcHeader.set_service_name(service_name);
    rpcHeader.set_method_name(method_name);
    rpcHeader.set_args_size(args_size);

    // 序列化
    uint32_t header_size = 0;
    std::string rpc_header_str;
    if (!rpcHeader.SerializeToString(&rpc_header_str))
    {
        std::cout << "serialize rpc_header_str error!" << std::endl;
        controller->SetFailed("serialize rpc_header_str error!");
        return;
    }
    else
    {
        header_size = rpc_header_str.size();
    }

    // // 将header_size转换为网络字节序
    // header_size = htonl(header_size);

    // 计算总长度并预分配空间
    size_t total_length = sizeof(uint32_t) + rpc_header_str.size() + args_str.size();
    std::string send_rpc_str;
    send_rpc_str.reserve(total_length); // 预分配空间

    // 构建发送数据包
    send_rpc_str.append((const char *)&header_size, sizeof(uint32_t)); // 添加header_size
    send_rpc_str.append(rpc_header_str);                               // 添加rpc_header_str
    send_rpc_str.append(args_str);                                     // 添加args_str

    // 打印调试信息
    std::cout << "================================================";
    std::cout << "header_size: " << header_size << std::endl;
    std::cout << "rpc_header_str: " << rpc_header_str << std::endl;
    std::cout << "service_name: " << service_name << std::endl;
    std::cout << "method_name: " << method_name << std::endl;
    std::cout << "args_size: " << args_size << std::endl;
    std::cout << "args_str: " << args_str << std::endl;
    std::cout << "================================================";

    // 使用tcp编程， 完成rpc方法的远程调用
    int clientfd = socket(AF_INET, SOCK_STREAM, 0);
    if (-1 == clientfd)
    {
        std::cout << "create socket error! errno:" << errno << std::endl;
        controller->SetFailed("create socket error! errno:" + std::to_string(errno));
        exit(EXIT_FAILURE);
    }

    // 使用智能指针管理 clientfd
    std::unique_ptr<int, decltype(fd_closer)> unique_clientfd(new int(clientfd), fd_closer);
    // // 使用std::function 作为删除器类型
    // std::unique_ptr<int, std::function<void (int*)> > unique_clientfd(new int(clientfd), fd_closer);

    // 读取固定的配置文件rpcserver的信息
    // std::string ip = MprpcApplication::GetInstance().GetConig().load("rpcserverip");
    // uint16_t port = static_cast<uint16_t>(std::stoul(MprpcApplication::GetInstance().GetConig().load("rpcserverport")));
    
    // rpc调用方法想调用service_name的method_name服务， 需要查询zookeeper上该服务所在的ip:host信息
    ZkClient zkCli;
    zkCli.Start();
    std::string method_path = '/' + service_name + '/' + method_name;
    std::string host_data = zkCli.GetData(method_path.c_str());
    if (host_data == "")
    {
        controller->SetFailed(method_path + "is not exists!");
        return;
    }
    int idx = host_data.find(":");
    if (idx == std::string::npos)
    {
        controller->SetFailed(method_path + "address is invalied!");
        return ;
    }

    std::string ip = host_data.substr(0, idx);
    uint16_t port = static_cast<uint16_t>(std::stoi(host_data.substr(idx + 1, host_data.size() - (idx + 1))));

    struct sockaddr_in server_addr;
    server_addr.sin_family = AF_INET;
    server_addr.sin_port = htons(port);
    if (inet_pton(AF_INET, ip.c_str(), &server_addr.sin_addr) <= 0)
    {
        std::cout << "Invalid address / address not supported!" << std::endl;
        controller->SetFailed("Invalid address / address not supported!");
        exit(EXIT_FAILURE);
    }

    // 连接rpc服务节点
    if (-1 == connect(clientfd, (struct sockaddr *)&server_addr, sizeof(server_addr)))
    {
        std::cout << "connect error! errno:" << errno << std::endl;
        controller->SetFailed("connect error! errno:"  + std::to_string(errno));
        exit(EXIT_FAILURE);
    }

    // 发送rpc请求
    if (-1 == send(clientfd, send_rpc_str.c_str(), send_rpc_str.size(), 0))
    {
        std::cout << "send error! errno:" << errno << std::endl;
        controller->SetFailed("send error! errno:"  + std::to_string(errno));
        return;
    }

    // 接收rpc请示的响应值
    char recv_buf[1024] = {0};
    int recv_size = 0;
    if (-1 == (recv_size = recv(clientfd, recv_buf, 1024, 0)))
    {
        std::cout << "recv error! errno:" << errno << std::endl;
        controller->SetFailed("recv error! errno:" + std::to_string(errno));
        return;
    }

    // 反序列化rpc调用 的响应数据
    std::string response_str(recv_buf, recv_size);
    if (!response->ParseFromString(response_str))
    {
        std::cout << "response->ParseFromString error! errno:" << errno << std::endl;
        controller->SetFailed("response->ParseFromString error! errno:" + std::to_string(errno));
        return;
    }
    
    return;
}
